import os

from celery.result import AsyncResult
from django.contrib.auth import authenticate, login, logout
from django.http import JsonResponse
from rest_framework.decorators import action
from rest_framework.viewsets import GenericViewSet, mixins

from common.page import page_
from mainapp.serializers import *
from common.error import *
from mainapp.tasks import create_news
from common.cliplist import clip_list
from mainapp.models import TChart
from mainapp.chart import *
from mainapp.HupuAll import get_hupu
from mainapp.geoSpider import get_citygeo
from mainapp.financeSpider import get_finance
from common.error import ERROR_CODE_OPERATION_FAILED


class UserApiView(GenericViewSet):
    queryset = TUser.objects.all()
    serializer_class = TUserSerializer

    # 注册
    @action(methods=["POST"], detail=False, serializer_class=CheckRegUserSerializer)
    def register(self, request):
        ser = self.get_serializer(data=request.data)  # 接收请求参数并将其封装到序列化对象（CheckRegUserSerializer）中
        try:
            ser.is_valid(raise_exception=True)
        except NewsException as e:
            info = {
                'successful': False,
                'data': None,
                'code': ERROR_CODE_OPERATION_FAILED,
                'message': e.detail
            }
            return JsonResponse(info, json_dumps_params={'ensure_ascii': False})
        username = ser.data.get("email", '')
        password = ser.data.get("password", '')
        user = TUser.objects.filter(username=username)
        if user:
            info = {
                'successful': False,
                'data': None,
                'code': ERROR_CODE_OPERATION_FAILED,
                'message': '该邮箱已注册'
            }
        else:
            new_user = TUser.objects.create_user(username=username, password=password)
            login(request, new_user)
            info = {
                'successful': True,
                'data': new_user.username,
                'code': ERROR_CODE_OPERATION_SUCCESS,
                'message': '注册成功，已登录'
            }
        return JsonResponse(info, json_dumps_params={'ensure_ascii': False})

    # 登录
    @action(methods=['POST'], detail=False)
    def login_(self, request):
        email = request.data.get('email', '')
        password = request.data.get('password', '')
        vaild = request.data.get('valid', '')
        user = authenticate(username=email, password=password)
        if user:
            # request.session["user_id"] = user.id  ####lynn
            login(request, user)
            info = {
                'successful': True,
                'data': user.username,
                'code': ERROR_CODE_OPERATION_SUCCESS,
                'message': '登录成功'
            }
            return JsonResponse(info, json_dumps_params={'ensure_ascii': False})
        else:
            info = {
                'successful': False,
                'data': None,
                'code': ERROR_CODE_OPERATION_FAILED,
                'message': '账户或密码错误'
            }
            return JsonResponse(info, json_dumps_params={'ensure_ascii': False})

    # 退出
    @action(methods=['GET'], detail=False)
    def logout_(self, request):
        logout(request)
        info = {
            'successful': True,
            'data': None,
            'code': ERROR_CODE_OPERATION_SUCCESS,
            'message': '退出成功'
        }
        return JsonResponse(info, json_dumps_params={'ensure_ascii': False})


class NewsApiView(GenericViewSet, mixins.CreateModelMixin, mixins.ListModelMixin):
    queryset = TNews.objects.all()
    serializer_class = TNewsSerializer

    # 历史记录
    def list(self, request, *args, **kwargs):
        kind = request.query_params.get("kind", '')
        page = request.query_params.get("page", '')
        uid = request.session.get('_auth_user_id', '1')  # lynn
        if uid:
            user = TUser.objects.get(pk=uid)
            p_ = (int(page) - 1) * 8
            p = int(page) * 8
            data = {}
            if kind == 'all':
                try:
                    allnews = TNews.objects.filter(user=user)[p_:p]
                    data['count'] = TNews.objects.filter(user=user).count()
                except NewsException as e:
                    info = {
                        'successful': False,
                        'data': None,
                        'code': ERROR_CODE_PARTNER_ERROR,
                        'message': e.detail
                    }
                    return JsonResponse(info, json_dumps_params={'ensure_ascii': False})
            elif kind == '1':
                try:
                    allnews = TNews.objects.filter(user=user, news_type=kind)[p_:p]
                    data['count'] = TNews.objects.filter(user=user, news_type=kind).count()
                except NewsException as e:
                    info = {
                        'successful': False,
                        'data': None,
                        'code': ERROR_CODE_PARTNER_ERROR,
                        'message': e.detail
                    }
                    return JsonResponse(info, json_dumps_params={'ensure_ascii': False})
            else:
                info = {
                    'successful': False,
                    'data': None,
                    'code': ERROR_CODE_PARTNER_ERROR,
                    'message': '该类型未开放'
                }
                return JsonResponse(info, json_dumps_params={'ensure_ascii': False})
            data['basketball'] = TNews.objects.filter(news_type=1).count()
            data['volleyball'] = TNews.objects.filter(news_type=2).count()
            data['other'] = TNews.objects.filter(news_type=3).count()
            data_dict = {}
            for news in allnews:
                data_ = {}
                clips = TClip.objects.filter(news=news)
                clip_d = {}
                count1 = 1
                for clip in clips:
                    clip_d[f'clip{count1}'] = clip.clip_path
                    count1 += 1
                imgs = TImage.objects.filter(news=news)
                img_d = {}
                count2 = 1
                for img in imgs:
                    img_d[f'img{count2}'] = img.image_path
                    count2 += 1
                data_['newsid'] = news.id
                data_['news_id'] = news.input_news_id
                data_['state'] = get_mission_result_local(news.input_news_id)
                data_['title'] = news.title
                data_['press_release'] = news.press_release
                data_['date'] = news.create_time.strftime('%Y-%m-%d %H:%M:%S %p')
                data_['newstype'] = news.news_type.typename
                data_['clips'] = clip_d
                data_['imgs'] = img_d
                data_dict[news.id] = data_
            data['value'] = data_dict
            info = {
                'successful': True,
                'data': data,
                'code': ERROR_CODE_OPERATION_SUCCESS,
                'message': '查询成功'
            }
        else:
            info = {
                'successful': False,
                'data': None,
                'code': ERROR_CODE_OPERATION_FAILED,
                'message': '请先登录'
            }
        return JsonResponse(info, json_dumps_params={'ensure_ascii': False})

    # 制作新闻
    def create(self, request, *args, **kwargs):
        videos = request.data.get('videos', '')
        title = request.data.get('title', '')
        news_id = request.data.get('news_id', '')
        txts = request.data.get('txts', '')
        news_type = request.data.get('news_type', '')
        uid = request.session.get('_auth_user_id', '1')  # lynn
        print(videos)
        if uid:
            if videos and title:
                data = {}
                task = create_news.delay(news_type=news_type, news_id=news_id,
                                         videos=videos, title=title, )
                data['task_id'] = task.id
                info = {
                    'successful': True,
                    'data': data,
                    'code': ERROR_CODE_OPERATION_SUCCESS,
                    'message': '新闻制作成功'
                }
            else:
                info = {
                    'successful': False,
                    'data': None,
                    'code': ERROR_CODE_PARTNER_ERROR,
                    'message': '上传参数不全'
                }
        else:
            info = {
                'successful': False,
                'data': None,
                'code': ERROR_CODE_OPERATION_FAILED,
                'message': '请先登录'
            }
        return JsonResponse(info, json_dumps_params={'ensure_ascii': False})

    # 确认发布
    @action(methods=['POST'], detail=False)
    def ensure_save(self, request):
        clips = request.data.get('clips', '')
        # imgs = request.data.get('imgs', '')
        news_id = request.data.get('news_id', '')
        title = request.data.get('title', '')
        press_release = request.data.get('press_release', '')
        news_type = request.data.get('news_type', '')
        code = request.data.get('code', '')
        uid = request.session.get('_auth_user_id', '1')  # lynn
        if uid:
            if code == 1:
                news_type_ = TNewsType.objects.get(pk=news_type)
                user = TUser.objects.get(pk=uid)
                news = TNews.objects.create(user=user, title=title, input_news_id=news_id,
                                            news_type=news_type_, press_release=press_release)
                for clip in clips:
                    TClip.objects.create(clip_path=clip, news=news)
                # for img in imgs:
                #     TImage.objects.create(image_path=img, news=news)
                info = {
                    'successful': True,
                    'data': None,
                    'code': ERROR_CODE_OPERATION_SUCCESS,
                    'message': '发布成功'
                }
                return JsonResponse(info, json_dumps_params={'ensure_ascii': False})
        else:
            info = {
                'successful': False,
                'data': None,
                'code': ERROR_CODE_OPERATION_FAILED,
                'message': '请先登录'
            }
            return JsonResponse(info, json_dumps_params={'ensure_ascii': False})

    # 搜索（标题或新闻id）
    @action(methods=['GET'], detail=False)
    def search(self, request):
        title = request.query_params.get("title", '')
        news_id = request.query_params.get("news_id", '')
        uid = request.session.get('_auth_user_id', '1')  # lynn
        if uid:
            user = TUser.objects.get(pk=uid)
            data = {}
            if title:
                try:
                    allnews = TNews.objects.filter(user=user, title=title)
                    data['count'] = TNews.objects.filter(user=user, title=title).count()
                except NewsException as e:
                    info = {
                        'successful': False,
                        'data': None,
                        'code': ERROR_CODE_PARTNER_ERROR,
                        'message': e.detail
                    }
                    return JsonResponse(info, json_dumps_params={'ensure_ascii': False})
            elif news_id:
                try:
                    allnews = TNews.objects.filter(user=user, input_news_id=news_id)
                    data['count'] = TNews.objects.filter(user=user, input_news_id=news_id).count()
                except NewsException as e:
                    info = {
                        'successful': False,
                        'data': None,
                        'code': ERROR_CODE_PARTNER_ERROR,
                        'message': e.detail
                    }
                    return JsonResponse(info, json_dumps_params={'ensure_ascii': False})
            else:
                info = {
                    'successful': False,
                    'data': None,
                    'code': ERROR_CODE_PARTNER_ERROR,
                    'message': '参数不全'
                }
                return JsonResponse(info, json_dumps_params={'ensure_ascii': False})
            data['basketball'] = TNews.objects.filter(news_type=1).count()
            data['volleyball'] = TNews.objects.filter(news_type=2).count()
            data['other'] = TNews.objects.filter(news_type=3).count()
            data_dict = {}
            for news in allnews:
                data_ = {}
                clips = TClip.objects.filter(news=news)
                clip_d = {}
                count1 = 1
                for clip in clips:
                    clip_d[f'clip{count1}'] = clip.clip_path
                    count1 += 1
                imgs = TImage.objects.filter(news=news)
                img_d = {}
                count2 = 1
                for img in imgs:
                    img_d[f'img{count2}'] = img.image_path
                    count2 += 1
                data_['newsid'] = news.id
                data_['news_id'] = news.input_news_id
                data_['title'] = news.title
                data_['press_release'] = news.press_release
                data_['date'] = news.create_time.strftime('%Y-%m-%d %H:%M:%S %p')
                data_['newstype'] = news.news_type.typename
                data_['clips'] = clip_d
                data_['imgs'] = img_d
                data_dict[news.id] = data_
            data['value'] = data_dict
            info = {
                'successful': True,
                'data': data,
                'code': ERROR_CODE_OPERATION_SUCCESS,
                'message': '查询成功'
            }
        else:
            info = {
                'successful': False,
                'data': None,
                'code': ERROR_CODE_OPERATION_FAILED,
                'message': '请先登录'
            }
        return JsonResponse(info, json_dumps_params={'ensure_ascii': False})

    # 新闻详情查询
    @action(methods=['GET'], detail=False)
    def list_one(self, request):
        newsid = request.query_params.get('newsid', '')
        uid = request.session.get('_auth_user_id', '1')  # lynn
        # uid = 1
        if uid:
            data = {}
            if newsid:
                res = page_(uid, newsid)
                news = TNews.objects.get(pk=newsid)
                clips = TClip.objects.filter(news=news)
                clips_ = []
                for clip in clips:
                    clips_.append(clip.clip_path)
                data['newsid'] = news.id
                data['news_id'] = news.input_news_id
                data['newstype'] = news.news_type.typename
                data['title'] = news.title
                data['press_release'] = news.press_release
                data['date'] = news.create_time.strftime('%Y-%m-%d %H:%M:%S %p')
                data['clips'] = clips_
                data['videos'] = get_mission_result_video(news.input_news_id)
                data['left'] = res.get('left', '')
                data['right'] = res.get('right', '')
                data['b_news'] = res.get('b_news', '')
                data['v_news'] = res.get('v_news', '')
                data['o_news'] = res.get('o_news', '')
                info = {
                    'successful': True,
                    'data': data,
                    'code': ERROR_CODE_OPERATION_SUCCESS,
                    'message': '查询成功'
                }
            else:
                info = {
                    'successful': False,
                    'data': None,
                    'code': ERROR_CODE_PARTNER_ERROR,
                    'message': '上传参数不全'
                }
        else:
            info = {
                'successful': False,
                'data': None,
                'code': ERROR_CODE_PARTNER_ERROR,
                'message': '还未登录'
            }
        return JsonResponse(info, json_dumps_params={'ensure_ascii': False})

    @action(methods=['GET'], detail=False)
    def del_one(self, request):
        newsid = request.query_params.get('newsid', '')
        uid = request.session.get('_auth_user_id', '1')  # lynn
        if uid:
            if newsid:
                news = TNews.objects.get(pk=newsid)
                clips = TClip.objects.filter(news=news)
                imgs = TImage.objects.filter(news=news)
                # chart = TChart.objects.get(match_id = ) #lynn 外键关联
                absdir = os.path.abspath(os.path.dirname(os.getcwd()))
                for clip in clips:
                    path_ = clip.clip_path.split('media')[1]
                    path = os.path.join(absdir, f'news_server/media{path_}')
                    if os.path.exists(path):
                        os.remove(path)
                    clip.delete()
                for img in imgs:
                    path_ = img.image_path.split('media')[1]
                    path = os.path.join(absdir, f'news_server/media{path_}')
                    if os.path.exists(path):
                        os.remove(path)
                    img.delete()
                news.delete()
                info = {
                    'successful': True,
                    'data': None,
                    'code': ERROR_CODE_OPERATION_SUCCESS,
                    'message': '删除成功'
                }
            else:
                info = {
                    'successful': False,
                    'data': None,
                    'code': ERROR_CODE_PARTNER_ERROR,
                    'message': '上传参数不全'
                }
        else:
            info = {
                'successful': False,
                'data': None,
                'code': ERROR_CODE_PARTNER_ERROR,
                'message': '还未登录'
            }
        return JsonResponse(info, json_dumps_params={'ensure_ascii': False})

    # 耗时任务获取结果
    @action(methods=['GET'], detail=False)
    def get_result(self, request):
        task_id = request.GET.get('task_id', '')
        uid = request.session.get('_auth_user_id', '1')  # lynn
        if uid:
            if task_id:
                res = AsyncResult(task_id)  # 参数为task id
                state = res.ready()
                if state:
                    data = res.result
                    return data
                else:
                    info = {
                        'successful': False,
                        'data': None,
                        'code': ERROR_CODE_OPERATION_FAILED,
                        'message': '正在生成'
                    }
            else:
                info = {
                    'successful': False,
                    'data': None,
                    'code': ERROR_CODE_OPERATION_FAILED,
                    'message': '没有该任务'
                }
        else:
            info = {
                'successful': False,
                'data': None,
                'code': ERROR_CODE_OPERATION_FAILED,
                'message': '还未登录'
            }
        return JsonResponse(info, json_dumps_params={'ensure_ascii': False})

    # 生成图表所用到的函数————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————

    # 搜索是否存在该比赛
    @action(methods=['GET'], detail=False)
    def chart_search_match(self, request):
        match_id = request.GET.get('match_id', '')
        # match_id = ID_Translator(match_id)  # ID 转换  lynn不应该转换吧？
        if match_id:
            try:
                allnews = TNews.objects.filter(input_news_id=match_id)
            except NewsException as e:
                info = {
                    'successful': False,
                    'data': None,
                    'code': ERROR_CODE_OPERATION_FAILED,
                    'message': '参数错误'
                }
                return JsonResponse(info, json_dumps_params={'ensure_ascii': False})

            data_dict = []
            for news in allnews:
                data_ = {'title': news.title, 'press_release': news.press_release}
                data_dict.append(data_)

            info = {
                'successful': False,
                'data': data_dict,
                'nba_id': match_id,
                'code': ERROR_CODE_OPERATION_FAILED,
                'message': '查找完成'
            }

            if data_dict:
                info['successful'] = True

                return JsonResponse(info, json_dumps_params={'ensure_ascii': False})
            else:
                info = {
                    'successful': False,
                    'data': None,
                    'code': ERROR_CODE_OPERATION_FAILED,
                    'message': '缺少数据'
                }
            return JsonResponse(info, json_dumps_params={'ensure_ascii': False})

    @action(methods=['GET'], detail=False)
    def get_videos(self, request):
        match_id = request.query_params.get('match_id', '')
        # match_id = ID_Translator(match_id)  # ID 转换 lynn这里不需要吧
        if match_id:
            name = clip_list(match_id)
            info = {
                'successful': True,
                'data': name,
                'code': ERROR_CODE_OPERATION_SUCCESS,
                'message': '获取视频成功'
            }
        else:
            info = {
                'successful': False,
                'data': None,
                'code': ERROR_CODE_PARTNER_ERROR,
                'message': '上传参数不全'
            }

        return JsonResponse(info, json_dumps_params={'ensure_ascii': False})

    # 增量上传视频
    @action(methods=['POST'], detail=False)
    def upload_videos(self, request):
        video = request.data.get('file', '')
        path_sys = 'E:\\proj\\chuanmei_news-kong_dev\\chuanmei_news-kong_dev\\news_server\\media'
        videos_root_dir_path = os.path.join(path_sys, f'{video.name}')
        vds = [video.name]
        with open(videos_root_dir_path, 'wb') as f:
            for chunk in video.chunks():
                f.write(chunk)
        info = {
            'successful': True,
            'data': vds,
            'code': ERROR_CODE_OPERATION_SUCCESS,
            'message': '上传视频成功'
        }
        return JsonResponse(info, json_dumps_params={'ensure_ascii': False})

    # 增量上传 BGM
    @action(methods=['POST'], detail=False)
    def upload_bgm(self, request):
        video = request.data.get('file', '')
        path_sys = 'E:\\proj\\chuanmei_news-kong_dev\\chuanmei_news-kong_dev\\news_server\\media\\bgm'
        videos_root_dir_path = os.path.join(path_sys, 'BGM')
        vds = [video.name]
        with open(videos_root_dir_path, 'wb') as f:
            for chunk in video.chunks():
                f.write(chunk)
        info = {
            'successful': True,
            'data': vds,
            'code': ERROR_CODE_OPERATION_SUCCESS,
            'message': '上传音频成功'
        }
        return JsonResponse(info, json_dumps_params={'ensure_ascii': False})

    @action(methods=['GET'], detail=False)
    def get_players(self, request):
        match_id = request.GET.get('match_id', '')
        match_id = ID_Translator(match_id)  # ID 转换 lynn这里需要
        return Search_match_id(match_id)

    @action(methods=['GET'], detail=False)
    def get_voices(self, request):
        match_id = request.GET.get('match_id', '')
        # match_id = ID_Translator(match_id)  # ID 转换 lynn 这里不需要转换吧？
        return chart_get_voices(match_id)  # lynn 音频位置修改

    # 获取文章的文字转语音
    @action(methods=["POST"], detail=False, serializer_class=CheckRegUserSerializer)
    def get_TtoV(self, request):
        art = request.data.get("art", '')
        match_id = str(request.data.get("match_id", ''))
        # match_id = ID_Translator(match_id)  # ID 转换 文章的是hupuid 不需要转换
        return chart_make_TtoV(art, match_id)  # article

    # 获取图表的文字转语音
    @action(methods=["POST"], detail=False, serializer_class=CheckRegUserSerializer)
    def get_TtoV_chart(self, request):
        type = request.data.get("type", '')
        name = request.data.get("name", '')
        match_id = str(request.data.get("match_id", ''))
        # match_id = ID_Translator(match_id)  # ID 转换，这里需要，但是要后置到函数内
        return chart_make_chart_TtoV(type, name, match_id)

    @action(methods=["GET"], detail=False, serializer_class=CheckRegUserSerializer)
    def chart_confirm_mission(self, request):
        match_id = str(request.data.get("match_id", ''))
        match_id = ID_Translator(match_id)  # ID 转换
        return chart_confirmission(match_id)

    @action(methods=["POST"], detail=False, serializer_class=CheckRegUserSerializer)
    def chart_add_mission(self, request):  # 提交图表制作任务
        match_id = str(request.data.get("match_id", ''))
        # match_id = ID_Translator(match_id)  # ID 转换 这里不用转换用hupuid
        type = request.data.get("type", '')
        name = request.data.get("name", '')
        chart_arr = [type, name]
        videos = request.data.get("videos", '')
        voice = request.data.get("voice", '')
        chart_voice = request.data.get("chart_voice", '')
        bgm = request.data.get("bgm", '')  # bgm是单个文件 与 上面的不同 lynn
        bgm = [bgm]  # lynn

        media_arr = {
            "video": videos,
            "voice": voice,
            "chart_voice": chart_voice,
            "bgm": bgm
        }
        # print(TChart.objects.filler(match_id=match_id))
        # if res["message"] = "递交成功":

        return add_mission(match_id, chart_arr, media_arr)

    # 生成图表所用到的函数————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————

    @action(methods=["POST"], detail=False, serializer_class=CheckRegUserSerializer)
    def hupu_crawler(self, request):  # 提交图表制作任务
        date = request.data.get("date", '')
        type = request.data.get("type", '')
        faddress = request.data.get("faddress", '')
        return get_hupu(date, type, faddress)

    @action(methods=["POST"], detail=False, serializer_class=CheckRegUserSerializer)
    def citygeo_crawler(self, request):  # 提交图表制作任务
        entity = request.data.get("entity", '')
        type = request.data.get("type", '')
        faddress = request.data.get("faddress", '')
        return get_citygeo(entity, type, faddress)

    @action(methods=["POST"], detail=False, serializer_class=CheckRegUserSerializer)
    def finance_crawler(self, request):  # 提交图表制作任务
        code_start = request.data.get("code_start", '')
        code_end = request.data.get("code_end", '')
        type = request.data.get("type", '')
        faddress = request.data.get("faddress", '')
        driver = request.data.get("driver", '')
        return get_finance(code_start, code_end, type, faddress, driver)

    # 爬虫所用到的函数————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————————

    # 获取剪辑视频
    @action(methods=['GET'], detail=False)
    def get_clips(self, request):
        news_id = request.query_params.get('news_id', '')
        uid = request.session.get('_auth_user_id', '1')  # lynn
        if uid:
            if news_id:
                clips = clip_list(news_id)
                info = {
                    'successful': True,
                    'data': clips,
                    'code': ERROR_CODE_OPERATION_SUCCESS,
                    'message': '获取视频成功'
                }
            else:
                info = {
                    'successful': False,
                    'data': None,
                    'code': ERROR_CODE_PARTNER_ERROR,
                    'message': '上传参数不全'
                }
        else:
            info = {
                'successful': False,
                'data': None,
                'code': ERROR_CODE_PARTNER_ERROR,
                'message': '还未登录'
            }
        return JsonResponse(info, json_dumps_params={'ensure_ascii': False})

    # 上传视频
    @action(methods=['POST'], detail=False)
    def save_videos(self, request):
        video = request.data.get('file', '')
        uid = request.session.get('_auth_user_id', '1')  # lynn
        if uid:
            path_sys = 'E:\\nba-short-video-unsupervised-reserved'
            videos_root_dir_path = os.path.join(path_sys, f'data\\videos\\{video.name}')
            with open(videos_root_dir_path, 'wb') as f:
                for chunk in video.chunks():
                    f.write(chunk)
            info = {
                'successful': True,
                'data': videos_root_dir_path,
                'code': ERROR_CODE_OPERATION_SUCCESS,
                'message': '上传视频成功'
            }
        else:
            info = {
                'successful': False,
                'data': None,
                'code': ERROR_CODE_OPERATION_FAILED,
                'message': '还未登录'
            }
        return JsonResponse(info, json_dumps_params={'ensure_ascii': False})

    # 删除上传的视频
    @action(methods=['POST'], detail=False)
    def del_videos(self, request):
        name = request.data.get('name', '')
        if name:
            try:
                os.remove(name)
                info = {
                    'successful': True,
                    'data': None,
                    'code': ERROR_CODE_OPERATION_SUCCESS,
                    'message': '删除成功'
                }
            except NewsException as e:
                info = {
                    'successful': False,
                    'data': None,
                    'code': ERROR_CODE_OPERATION_FAILED,
                    'message': e.detail
                }
        else:
            info = {
                'successful': False,
                'data': None,
                'code': ERROR_CODE_OPERATION_FAILED,
                'message': '没有文件名'
            }
        return JsonResponse(info, json_dumps_params={'ensure_ascii': False})

    # 上传文本
    @action(methods=['POST'], detail=False)
    def save_txts(self, request):
        txt = request.data.get('file', '')
        # c = request.data.get('c', '')
        uid = request.session.get('_auth_user_id', '1')  # lynn
        if uid:
            path_sys = 'D:\\writeBot\\untitled\\'
            if 'playbyplay' in txt.name:
                path_ = path_sys + r'textlive'
            elif 'recap' in txt.name:
                path_ = path_sys + r'news'
            elif 'boxscore' in txt.name:
                path_ = path_sys + r'playerData'
            if not os.path.exists(path_):
                os.makedirs(path_)
            txt_path = f'{path_}\{txt.name}'
            with open(txt_path, 'wb') as f:
                for chunk in txt.chunks():
                    f.write(chunk)
            # c_ = int(c) + 1
            info = {
                'successful': True,
                'data': txt_path,
                'code': ERROR_CODE_OPERATION_SUCCESS,
                'message': '上传文本成功'
            }
        else:
            info = {
                'successful': False,
                'data': None,
                'code': ERROR_CODE_OPERATION_FAILED,
                'message': '还未登录'
            }
        return JsonResponse(info, json_dumps_params={'ensure_ascii': False})

    # 删除上传的文本
    @action(methods=['POST'], detail=False)
    def del_txts(self, request):
        name = request.data.get('name', '')
        if name:
            try:
                for n in name:
                    os.remove(n)
                info = {
                    'successful': True,
                    'data': None,
                    'code': ERROR_CODE_OPERATION_SUCCESS,
                    'message': '删除成功'
                }
            except NewsException as e:
                info = {
                    'successful': False,
                    'data': None,
                    'code': ERROR_CODE_OPERATION_FAILED,
                    'message': e.detail
                }
        else:
            info = {
                'successful': False,
                'data': None,
                'code': ERROR_CODE_OPERATION_FAILED,
                'message': '没有文件名'
            }
        return JsonResponse(info, json_dumps_params={'ensure_ascii': False})
